/*
 *   Copyright (c) 2010-2022, SIUFUNG
 */
package net.siufung.market.base.dict.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.common.base.Strings;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.siufung.core.exception.BizServiceException;
import net.siufung.core.model.enums.DeletedEnum;
import net.siufung.market.base.dict.mapper.IDictMapper;
import net.siufung.market.base.dict.mapper.IDictTypeMapper;
import net.siufung.market.base.dict.mapper.entity.Dict;
import net.siufung.market.base.dict.mapper.entity.DictType;
import net.siufung.market.base.dict.service.IDictService;
import net.siufung.mybatis.base.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Objects;

/**
 * 字典数据 数据服务实现
 *
 * @author 陈建峰
 * @since 2022-07-08 15:30:15
 */
@Slf4j
@AllArgsConstructor
@Service(value = "dictService")
@Transactional(rollbackFor = Exception.class)
public class DictServiceImpl extends BaseServiceImpl<IDictMapper, Dict> implements IDictService {

    private final IDictTypeMapper dictTypeMapper;

    @Override
    public boolean save(Dict entity) {
        if(Strings.isNullOrEmpty(entity.getDictCode())){
            entity.setDictCode(getBaseMapper().getRandomCode(16));
        }
        if(Objects.nonNull(entity.getDictTypeId())){
            DictType dictType = dictTypeMapper.selectById(entity.getDictTypeId());
            if(Objects.isNull(dictType)){
                throw new BizServiceException("字典类型数据异常！");
            }
            entity.setDictTypeCode(dictType.getTypeCode());
        }
        return super.save(entity);
    }

    @Override
    public boolean updateStatusById(Serializable id, DeletedEnum deletedEnum) {
        return super.update(
                new LambdaUpdateWrapper<Dict>()
                        .eq(Dict::getId, id)
                        .set(Dict::getDeleted, deletedEnum.getValue()));
    }
}